package com.zcxy.handler;


import com.zcxy.constant.CommonConstant;
import com.zcxy.core.bean.Response;
import com.zcxy.exception.BusinessException;
import com.zcxy.exception.CustomerAuthException;
import com.zcxy.util.MessageSourceUtil;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.Set;

/**
 * 全局异常处理器
 *
 * @author
 */
@RestControllerAdvice
@Log4j2
public class GlobalExceptionHandler {

    @Autowired
    private MessageSourceUtil messageSourceUtil;

    /**
     * 请求方式不支持
     */
    @ExceptionHandler({HttpRequestMethodNotSupportedException.class})
    public Response handleException(HttpRequestMethodNotSupportedException e) {
        log.error(e.getMessage(), e);
        return Response.error(200, "不支持' " + e.getMethod() + "'请求");
    }

    /**
     * 参数json化异常
     */
    @ExceptionHandler({HttpMessageNotReadableException.class})
    public Response jsonException(HttpMessageNotReadableException e) {
        log.error(e.getMessage(), e);
        if (e.getMessage().contains("JSON parse error")) {
            return Response.error(CommonConstant.SC_INTERNAL_SERVER_ERROR_400,
                    messageSourceUtil.getMessage("comm.json.error", null, e.getMessage()));
        }
        String message = messageSourceUtil.getMessage("comm.param.error", null, e.getMessage());
        return Response.error(CommonConstant.SC_INTERNAL_SERVER_ERROR_400, message);
    }

    /**
     * 参数丢失异常
     */
    @ExceptionHandler({MissingServletRequestParameterException.class})
    public Response paramException(MissingServletRequestParameterException e) {
        log.error(e.getMessage(), e);
        return Response.error(CommonConstant.SC_INTERNAL_SERVER_ERROR_400, e.getMessage());
    }

    /**
     * 拦截未知的运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    public Response notFount(RuntimeException e) {
        log.error("运行时异常:", e);
        return Response.error("运行时异常:" + e.getMessage());
    }

    /**
     * 系统异常
     */
    @ExceptionHandler(Exception.class)
    public Response handleException(Exception e) {
        log.error(e.getMessage(), e);
        return Response.error("服务器错误，请联系管理员");
    }

    /**
     * 业务异常
     */
    @ExceptionHandler(BusinessException.class)
    public Object businessException(HttpServletRequest request, BusinessException e) {
        String message = messageSourceUtil.getMessage(e.getCode(), e.getParams(), e.getMessage());
        log.error(message, e);
        return Response.error(400, message);
    }







    /**
     * 业务异常
     */
    @ExceptionHandler(CustomerAuthException.class)
    public Object customerAuthException(HttpServletRequest request, CustomerAuthException e) {
        return Response.error(HttpStatus.FORBIDDEN.value(), "无权访问(Unauthorized):" + e.getMessage());
    }

    /**
     * 处理请求参数格式错误 @RequestParam上validate失败后抛出的异常是javax.validation.ConstraintViolationException
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public Response constraintViolationException(ConstraintViolationException e) {
        Set<ConstraintViolation<?>> errors = e.getConstraintViolations();
        StringBuilder sb = new StringBuilder();
        for (ConstraintViolation<?> violation : errors) {
            sb.append(violation.getMessage() + "\n");
        }
        return Response.error(CommonConstant.SC_INTERNAL_SERVER_ERROR_400, sb.toString());
    }

    /**
     * 处理请求参数格式错误 @RequestBody上validate失败后抛出的异常是MethodArgumentNotValidException异常。
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Response methodArgumentNotValidException(MethodArgumentNotValidException e) {
        log.error(e.getMessage(), e);
        String message = e.getBindingResult().getAllErrors().get(0).getDefaultMessage();
        return Response.error(CommonConstant.SC_INTERNAL_SERVER_ERROR_400, message);
    }

    /**
     * 自定义验证异常
     */
    @ExceptionHandler(BindException.class)
    public Response validatedBindException(BindException e) {
        log.error(e.getMessage(), e);
        String message = e.getAllErrors().get(0).getDefaultMessage();
        return Response.error(200, message);
    }

    /**
     * 获取状态码
     *
     * request
     * @return
     */
    private HttpStatus getStatus(HttpServletRequest request) {
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        if (statusCode == null) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }
        return HttpStatus.valueOf(statusCode);
    }
}
